using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using ValidationFramework.Extensions;
using ValidationFramework.Reflection;

namespace ValidationFramework.Web.ASP
{
    public class RangeRuleClientValidationGenerator : IClientValidationGenerator
    {
      

		/// <inheritdoc />
        public IList<BaseValidator> CreateWebClientValidators(Rule rule, InfoDescriptor infoDescriptor)
		{
		    var validationDataType = ValidatorCreatorHelper.GetValidationDataType(infoDescriptor.RuntimeTypeHandle);
		    var rangeWebValidatorEx = new RangeWebValidatorEx();
		    var validationDataTypeValue = validationDataType.Value;
		    rangeWebValidatorEx.Type = validationDataType.Value;

		    if (validationDataTypeValue == ValidationDataType.Date)
		    {
		        var minimumAsDateTime = (DateTime) rule.GetPropertyValue("Minimum");
		        var maximumAsDateTime = (DateTime) rule.GetPropertyValue("Maximum");
		        if (minimumAsDateTime.TimeOfDay != TimeSpan.Zero || maximumAsDateTime.TimeOfDay != TimeSpan.Zero)
		        {
		            return null;
		        }
		        else
		        {
		            rangeWebValidatorEx.MinimumValue = minimumAsDateTime.ToString("yyyy-MM-dd");
		            rangeWebValidatorEx.MaximumValue = maximumAsDateTime.ToString("yyyy-MM-dd");
		        }
		    }
		    else
		    {
		        rangeWebValidatorEx.MinimumValue = rule.GetPropertyValue("Minimum").ToString();
		        rangeWebValidatorEx.MaximumValue = rule.GetPropertyValue("Maximum").ToString();
		    }

		    var list = new List<BaseValidator> {rangeWebValidatorEx};
		    return list;
		}

        /// <inheritdoc />
        public bool CanHandleTarget(RuleContext ruleContext)
        {
            var rule = ruleContext.Rule;
        	var type = rule.GetType();
        	if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(RangeRule<>))
			{
				if ((bool) rule.GetPropertyValue("EqualsMinimumIsValid") && (bool) rule.GetPropertyValue("EqualsMaximumIsValid"))
				{
					var validationDataType = ValidatorCreatorHelper.GetValidationDataType(ruleContext.InfoDescriptor.RuntimeTypeHandle);
					return validationDataType.HasValue;
				}
			}

        	return false;
        }
    }
}